<template>
  <div class="add-department-container">
    <!-- 顶部导航区域 -->
    <div class="header-wrapper">
      <!-- 顶部导航 -->
      <div class="header">
        <!-- <van-icon name="arrow-left" class="back-icon" @click="goBack" /> -->
        <div class="header-back" @click="goBack">取消</div>
        <div class="header-title">{{ isEditMode ? '部门管理' : '添加子部门' }}</div>
        <div class="header-action" @click="handleComplete" v-if="!isEditMode">完成</div>
        <!-- <div class="header-action delete-action" @click="deleteDepartment" v-if="isEditMode">删除</div> -->
      </div>
    </div>

    <!-- 表单内容 -->
    <div class="form-container">
      <!-- 部门名称 -->
      <div class="form-item">
        <div class="form-label">部门名称</div>
        <van-field
          v-model="departmentName"
          placeholder="必填"
          :border="false"
          class="custom-field"
          autocomplete="off"
          :readonly="isEditMode"
        />
      </div>

      <!-- 部门主管 -->
      <div class="form-item" @click="selectManager">
        <div class="form-label">部门主管</div>
        <div class="form-value">
          <span v-if="selectedManager" class="selected-manager">{{ selectedManager.name }}</span>
          <span v-else class="placeholder">请选择</span>
          <van-icon name="arrow" class="arrow-icon" v-if="!isEditMode" />
        </div>
      </div>

      <!-- 简介 -->
      <div class="form-item">
        <div class="form-label">简介</div>
        <van-field
          autocomplete="off"
          v-model="description"
          placeholder="选填"
          :border="false"
          class="custom-field"
          :readonly="isEditMode"
        />
      </div>

      <!-- 部门电话 -->
      <div class="form-item">
        <div class="form-label">部门电话</div>
        <van-field
          type="tel"
          v-model="phone"
          placeholder="选填"
          :border="false"
          class="custom-field"
          autocomplete="off"
          :readonly="isEditMode"
        />
      </div>

      <!-- 上级部门 -->
      <div class="form-item">
        <div class="form-label">上级部门</div>
        <div class="form-value">
          <span class="parent-department">{{ parentDepartmentName }}</span>
        </div>
      </div>
    </div>
    
    <!-- 删除部门按钮 -->
    <!-- <div class="delete-department-btn" v-if="isEditMode" @click="deleteDepartment">
      <span>删除部门</span>
    </div> -->
    <!-- 删除主管 -->
     <!-- <div class="delete-department-btn" v-if="isEditMode" @click="deleteDepartment">
      <span>删除部门主管</span>
    </div> -->
      <div class="bottom-actions">
      <div class="action-buttons">
        <div class="action-btn delete-btn"  v-if="isEditMode" @click="deleteDepartment">
          <span>删除部门</span>
        </div>
        <div class="action-btn resign-btn" v-if="isEditMode" @click="removeLeader">
          <span>删除部门主管</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showDialog } from 'vant'
import { getAllDepartments, findDepartmentById, getNoDepartmentMembers, addDepartment, getDepartmentDetail, removeDepartment, type NoDepartmentMember, type AddDepartmentRequest, type DepartmentMember, type DepartmentDetailData,getRemoveLeader } from '@/api/organization'
import { smartGoBack } from '@/utils/navigation'

// 路由实例
const router = useRouter()
const route = useRoute()

// 表单数据
const departmentName = ref('')
const description = ref('')
const phone = ref('')
const selectedManager = ref<NoDepartmentMember | null>(null)

// 无部门成员列表
const noDepartmentMembers = ref<NoDepartmentMember[]>([])

// 来源页面信息
const fromPage = ref<string>('')
const parentDepartmentId = ref<string>('')
const parentDepartmentName = ref<string>('')

// 是否为编辑模式（从部门页面跳转来）
const isEditMode = ref(false)

// 部门映射
const departmentMap: Record<string, any> = {
  'root': {
    id: 'root',
    name: '北京君初律师事务所'
  },
  'hr': {
    id: 'hr',
    name: '人力资源部'
  },
  'finance': {
    id: 'finance',
    name: '总经办'
  },
  'rd': {
    id: 'rd',
    name: '研发部'
  },
  'tech': {
    id: 'tech',
    name: '技术部'
  },
  'art': {
    id: 'art',
    name: '美术部'
  },
  'sales': {
    id: 'sales',
    name: '销售部'
  }
}

// 返回上一页
const goBack = () => {
  smartGoBack(router)
}

// 获取无部门成员列表
const loadNoDepartmentMembers = async () => {
  try {
    const response = await getNoDepartmentMembers()
    if (response.code === 0) {
      noDepartmentMembers.value = response.data
      console.log('无部门成员数据加载成功:', response.data)
    } else {
      showToast(response.msg || '获取成员列表失败')
    }
  } catch (error) {
    console.error('获取无部门成员失败:', error)
    showToast('获取成员列表失败，请稍后重试')
  }
}

// 选择主管
const selectManager = () => {
  if (isEditMode.value) return
  
  // 保存当前表单数据到sessionStorage
  const formData = {
    departmentName: departmentName.value,
    description: description.value,
    phone: phone.value,
    parentDepartmentName: parentDepartmentName.value
  }
  sessionStorage.setItem('add-department-form', JSON.stringify(formData))
  console.log('保存表单数据到sessionStorage:', formData)
  
  // 跳转到设置主管页面
  router.push({
    path: '/organization/set-manager',
    query: {
      from: 'add-department',
      parentId: parentDepartmentId.value,
      mode: route.query.mode, // 传递mode参数
      originalFrom: fromPage.value // 传递原始来源页面
    }
  })
}

// 完成添加
const handleComplete = async () => {
  // 如果是编辑模式，不执行添加操作
  if (isEditMode.value) {
    return
  }
  
  // 表单验证
  if (!departmentName.value.trim()) {
    showToast('请填写部门名称')
    return
  }
  
  if (phone.value.trim() && !/^1[3-9]\d{9}$/.test(phone.value.trim())) {
    showToast('请输入正确的手机号')
    return
  }
  
  // if (!selectedManager.value) {
  //   showToast('请选择部门主管')
  //   return
  // }
  
  try {
    // 构建请求数据
    const departmentData: AddDepartmentRequest = {
      name: departmentName.value.trim(),
      remark: description.value.trim(),
      phone: phone.value.trim(),
      leader: selectedManager?.value?.id?.toString() || ''
    }
    
    console.log('提交部门数据:', departmentData)
    
    // 调用添加部门API
    const response = await addDepartment(departmentData)
    
    if (response.code === 0) {
      showToast('添加成功')
      
      // 根据来源页面返回对应页面
      setTimeout(() => {
        if (fromPage.value === 'department' && parentDepartmentId.value) {
          router.push(`/organization/department/${parentDepartmentId.value}`)
        } else {
          router.push('/organization')
        }
      }, 1500)
    } else {
      showToast(response.msg || '添加失败')
    }
  } catch (error) {
    console.error('添加部门失败:', error)
    showToast('添加失败，请重试')
  }
}

// 删除部门
const deleteDepartment = () => {
  showDialog({
    title: '删除部门',
    message: `确定要删除${departmentName.value}部门吗？`,
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    // 确认删除
    try {
      console.log('🗑️ 开始删除部门:', parentDepartmentId.value)
      const response = await removeDepartment(parentDepartmentId.value)
      console.log('🗑️ 删除部门API响应:', response)
      
      if (response.code === 0) {
        showToast('删除成功')
        // 延迟返回上一页
        setTimeout(() => {
          if (fromPage.value === 'department') {
            router.push('/organization')
          } else {
            router.back()
          }
        }, 1500)
      } else {
        showToast(response.msg || '删除失败')
      }
    } catch (error) {
      console.error('❌ 删除部门异常:', error)
      showToast('删除失败，请重试')
    }
  }).catch(() => {
    // 取消删除
    console.log('用户取消删除操作')
  })
}
// 删除部门主管

const removeLeader = () => {
  showDialog({
    title: '删除部门主管',
    message: `确定要删除${departmentName.value}部门的主管？`,
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    // 确认删除
    try {
      console.log('🗑️ 开始删除部门:', parentDepartmentId.value)
      const response = await getRemoveLeader(parentDepartmentId.value)
      console.log('🗑️ 删除部门API响应:', response)
      
      if (response.code === 0) {
        showToast('删除成功')
        // 延迟返回上一页
        setTimeout(() => {
          if (fromPage.value === 'department') {
            router.push('/organization')
          } else {
            router.back()
          }
        }, 1500)
      } else {
        showToast(response.msg || '删除失败')
      }
    } catch (error) {
      console.error('❌ 删除部门异常:', error)
      showToast('删除失败，请重试')
    }
  }).catch(() => {
    // 取消删除
    console.log('用户取消删除操作')
  })
}
// 页面初始化
onMounted(async () => {
  // 首先初始化基础路由参数
  fromPage.value = route.query.from as string || 'index'
  parentDepartmentId.value = route.query.parentId as string || 'root'
  
  // 判断是否为编辑模式：检查URL中是否有mode=edit参数
  const mode = route.query.mode as string
  isEditMode.value = mode === 'edit'
  
  // 处理从set-manager页面返回的主管信息
  const selectedManagerId = route.query.selectedManagerId as string
  const selectedManagerName = route.query.selectedManagerName as string
  const selectedManagerPosition = route.query.selectedManagerPosition as string
  
  console.log('🔍 检查路由参数:', {
    selectedManagerId,
    selectedManagerName,
    selectedManagerPosition,
    allQuery: route.query
  })
  
  // 如果有选中的主管信息，说明是从set-manager页面返回的
  if (selectedManagerId && selectedManagerName) {
    selectedManager.value = {
      id: parseInt(selectedManagerId),
      name: selectedManagerName,
      phone: '',
      admin: 0,
      department: -1,
      ceo: 0,
      hr: 0,
      url: '',
      position: selectedManagerPosition || ''
    }
    console.log('已接收选中的主管信息:', selectedManager.value)
    
    // 从sessionStorage恢复表单数据
    const savedFormData = sessionStorage.getItem('add-department-form')
    if (savedFormData) {
      try {
        const formData = JSON.parse(savedFormData)
        departmentName.value = formData.departmentName || ''
        description.value = formData.description || ''
        phone.value = formData.phone || ''
        parentDepartmentName.value = formData.parentDepartmentName || ''
        console.log('从sessionStorage恢复表单数据:', formData)
        // 清除sessionStorage中的数据
        sessionStorage.removeItem('add-department-form')
      } catch (error) {
        console.error('解析sessionStorage数据失败:', error)
      }
    } else {
      console.log('未找到sessionStorage中的表单数据')
    }
    
    // 设置上级部门名称（如果sessionStorage中没有保存）
    if (!parentDepartmentName.value) {
      const parentDept = departmentMap[parentDepartmentId.value]
      if (parentDept) {
        parentDepartmentName.value = parentDept.name
      } else {
        parentDepartmentName.value = '北京君初律师事务所'
      }
    }
    
    console.log('从set-manager返回，保留表单数据:', {
      departmentName: departmentName.value,
      description: description.value,
      phone: phone.value,
      parentDepartmentName: parentDepartmentName.value,
      selectedManager: selectedManager.value
    })
    
    // 不再调用router.replace，避免组件重新挂载导致数据丢失
    // 保持URL参数不变，确保数据正确显示
    
    return // 直接返回，不执行后续的初始化逻辑
  }
  
  // 设置上级部门名称
  const parentDept = departmentMap[parentDepartmentId.value]
  console.log(parentDept,'--parentDept');
  if (parentDept) {
    parentDepartmentName.value = parentDept.name
    
  } else {
    parentDepartmentName.value = '北京君初律师事务所'
  }
  
  // 获取部门详情
  const loadDepartmentDetail = async (departmentId: string, skipManagerLoad = false) => {
    console.log('🔍 开始加载部门详情:', { departmentId, skipManagerLoad, isEditMode: isEditMode.value })
    
    try {
      // 获取部门基本信息
      console.log('📡 调用getDepartmentDetail API:', departmentId)
      const detailResponse = await getDepartmentDetail(departmentId)
      console.log('📡 getDepartmentDetail API响应:', detailResponse)
      
      if (detailResponse.code === 0) {
        const detail = detailResponse.data
        console.log('✅ 部门详情数据:', detail)
        
        // 设置部门基本信息
        departmentName.value = detail.name
        description.value = detail.remark || ''
        phone.value = detail.phone || ''
        
        console.log('✅ 部门基本信息已设置:', {
          name: departmentName.value,
          remark: description.value,
          phone: phone.value
        })
        
        // 如果不跳过主管加载且当前没有选中的主管，则获取部门成员信息以找到主管
        if (!skipManagerLoad && !selectedManager.value) {
          console.log('📡 调用findDepartmentById API获取成员信息:', departmentId)
          const membersResponse = await findDepartmentById(departmentId)
          console.log('📡 findDepartmentById API响应:', membersResponse)
          
          if (membersResponse.code === 0) {
            const members = membersResponse.data
            // 找到主管 - 根据detail.leader字段匹配成员ID
            const leader = members.find((member: DepartmentMember) => member.id === detail.leader)
            console.log('👤 查找主管结果:', { 
              members, 
              leaderId: detail.leader, 
              leader 
            })
            
            if (leader) {
              selectedManager.value = {
                id: leader.id,
                name: leader.name,
                phone: '',
                admin: 0,
                department: parseInt(departmentId),
                ceo: 0,
                hr: 0,
                url: leader.url,
                position: '主管'
              }
              console.log('✅ 部门主管信息设置成功:', selectedManager.value)
            } else {
              console.log('⚠️ 未找到部门主管，leaderId:', detail.leader)
            }
          } else {
            console.log('❌ 获取部门成员失败:', membersResponse.msg)
          }
        } else {
          console.log('⏭️ 跳过主管加载:', { skipManagerLoad, hasSelectedManager: !!selectedManager.value })
        }
      } else {
        console.log('❌ 获取部门详情失败:', detailResponse.msg)
        showToast(detailResponse.msg || '获取部门详情失败')
      }
    } catch (error) {
      console.error('❌ 获取部门详情异常:', error)
      showToast('获取部门详情失败，请稍后重试')
    }
    
    console.log('🏁 loadDepartmentDetail函数执行完成')
  }

  // 如果不是编辑模式，预加载无部门成员数据
  if (!isEditMode.value) {
    await loadNoDepartmentMembers()
  } else {
    // 如果是编辑模式且不是从set-manager返回，加载部门详情
    // 从set-manager返回时已经有了表单数据，不需要重新加载
    const isFromSetManager = selectedManagerId && selectedManagerName
    if (isEditMode.value && parentDepartmentId.value && !isFromSetManager) {
      await loadDepartmentDetail(parentDepartmentId.value)
    }
  }
  
  console.log('首次加载部门管理页面', { 
    fromPage: fromPage.value, 
    parentDepartmentId: parentDepartmentId.value,
    parentDepartmentName: parentDepartmentName.value,
    isEditMode: isEditMode.value,
    mode: mode,
    departmentName: departmentName.value,
    description: description.value,
    phone: phone.value
  })
})
</script>

<style lang="scss" scoped>
@import url('./style/add-department.scss');
</style>